package com.starlight.easybuyprictice.interceptor;

import com.starlight.easybuyprictice.entity.Token;
import com.starlight.easybuyprictice.util.WebUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author yfy2001
 * @date 2022/11/28 20:39
 */
@Component
public class RoleInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Token.Type userRole = (Token.Type)request.getAttribute(Constants.CURRENT_USER_ROLE);
        if (userRole == null) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RoleAuthentication annotation = method.getAnnotation(RoleAuthentication.class);
        if (annotation == null) {
            return true;
        }
        if (Arrays.asList(annotation.roles()).contains(userRole)) {
            return true;
        }
        WebUtil.showInterceptionInfo(response, -2, " 您当前没有使用该功能的权限");
        return false;
    }
}